import axios from 'axios'
import { useAuthStore } from '@/store/auth'
import { ElMessage } from 'element-plus'

const apiClient = axios.create({
  baseURL: 'http://localhost:8080/api',
  withCredentials: false,
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
apiClient.interceptors.request.use(config => {
  const authStore = useAuthStore()
  if (authStore.token) {
    config.headers.Authorization = `Bearer ${authStore.token}`
  }
  return config
}, error => {
  let errorMessage = 'Request failed'
  
  if (error.response) {
    // 服务器返回的错误
    errorMessage = error.response.data?.message || 
                 `Server error: ${error.response.status}`
  } else if (error.request) {
    // 请求已发出但没有响应
    errorMessage = 'Network error: No response from server'
  } else {
    // 其他错误
    errorMessage = error.message || 'Request failed'
  }
  
  ElMessage.error(errorMessage)
  
  return Promise.reject(error)
})

// 响应拦截器 - 处理token刷新
apiClient.interceptors.response.use(response => {
  return response
}, async error => {
  const originalRequest = error.config
  const authStore = useAuthStore()
  
  // 401错误且不是刷新token请求
  if (error.response?.status === 401 && !originalRequest._retry) {
    originalRequest._retry = true
    
    try {
      await authStore.refreshToken()
      // 更新请求头
      originalRequest.headers.Authorization = `Bearer ${authStore.token}`
      // 重试原始请求
      return apiClient(originalRequest)
    } catch (refreshError) {
      authStore.resetAuthState()
      return Promise.reject(refreshError)
    }
  }
  
  return Promise.reject(error)
})

// 导入各模块API
import auth from './auth'
import user from './user'
import role from './role'
import permission from './permission'
import log from './log'

export { apiClient }
export default {
  auth,
  user, 
  role,
  permission,
  log
}
